package com.zxq.kingofbots.service.impl.user.bot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxq.kingofbots.mapper.BotMapper;
import com.zxq.kingofbots.pojo.Bot;
import com.zxq.kingofbots.pojo.User;
import com.zxq.kingofbots.service.impl.utils.UserDetailsImpl;
import com.zxq.kingofbots.service.user.bot.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UpdateServiceImpl implements UpdateService {
    @Autowired
    private BotMapper botMapper;
    @Override
    public Map<String, String> updateBot(Map<String, String> data) {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();

        Map<String,String> map=new HashMap<>();
        int id=Integer.parseInt(data.get("id"));
        String title=data.get("title");
        String description=data.get("description");
        String content=data.get("content");

        Bot bot = botMapper.selectById(id);
        if(bot==null){
            map.put("message","该bot不存在");
            return map;
        }

        if(!bot.getUserId().equals(user.getId())){
            map.put("message","非该bot主人，不能修改该bot");
            return map;
        }

        if(title==null|| title.isEmpty()){
            title="新建bot";
        }

        if(title.length()>100){
            map.put("message","标题不能超过100字符");
            return map;
        }

        if(description==null|| description.isEmpty()){
            description="该用户很懒，什么也没留下";
        }

        if(description.length()>300){
            map.put("message","描述不能超过300字符");
            return map;
        }

        if(content.length()>10000){
            map.put("message","内容不能超过10000字符");
            return map;
        }
        Date now=new Date();
        Bot newBot=new Bot(bot.getId(),bot.getUserId(),title,description,content,bot.getCreateTime(),now);

        botMapper.updateById(newBot);
        map.put("message","success");
        return map;
    }
}
